<template>
	<div class="zh-video-settings">
		<nav-header></nav-header>
		<div class="zh-video-test"
			v-loading="loading.status"
			:element-loading-text="loading.txt">
            <h3 style="margin-top: 0;padding-top: 0">视频上传设置</h3>
            <div class="zh-video-directions">前台用户视频上传大小(M)</div>
            <div class="zh-video-number">
                <el-input-number v-model="uploadParam.teacher_max_size" :controls="false" :min="0" :max="99999" @change="proving">
                </el-input-number>
                <span style="color: #999">可上传视频大于或等于0的正整数，0表示不限制</span>
            </div>
            
            <div class="zh-video-directions">管理员视频上传大小(M)</div>
            <div class="zh-video-number">
                <el-input-number v-model="uploadParam.manage_max_size" :controls="false" :min="0" :max="99999" @change="manageSise">
                </el-input-number>
                <span style="color: #999">可上传视频大于或等于0的正整数，0表示不限制</span>
            </div>
            <el-button type="primary" @click="saveUploadSetting">保存设置</el-button>

            <h3>视频转码设置</h3>
            <div class="zh-video-directions">立即转码<span style="color: #999">(在设置范围内的视频上传就会立即转码)</span></div>
            <div class="zh-video-number">
                <el-input-number v-model="transformParam.immediately_size" :controls="false" :min="0" :max="99999" @change="immediatelySise">
                </el-input-number>
                <span style="color: #999">输入最大视频大小(M)视频大于或等于0的正整数，0表示不限制</span>
            </div>
            <div class="zh-video-directions">空闲时转码<span style="color: #999">(超过转码限制大小的视频会在设置时间段按顺序解码)</span></div>
            <div class="zh-video-number">
                <el-time-select
                    placeholder="起始时间"
                    :editable="false"
                    v-model="transformParam.work_start_time"
                    :picker-options="{
                        start: '00:00',
                        step: '00:30',
                        end: '23:59'
                    }">
                </el-time-select>
                <span style="color: #999">-</span>
                <el-time-select
                    placeholder="结束时间"
                    :editable="false"
                    v-model="transformParam.work_end_time"
                    :picker-options="{
                        start: '00:00',
                        step: '00:30',
                        end: '23:59',
                        minTime:transformParam.work_start_time
                    }">
                </el-time-select>
            </div>
            <el-button type="primary" :disabled="saveTransformSetFlag" @click="saveTransformSetting">保存设置</el-button>

            <h3>视频保存设置</h3>
            <div>
                <div class="video-duration">将对所有视频进行保存设置</div>
                <el-radio-group v-model="saveDuration" class="video-month">
                    <el-radio :label="1">永久保存</el-radio>
                    <el-radio :label="2">三个月</el-radio>
                    <el-radio :label="3">半年</el-radio>
                    <el-radio :label="4">一年</el-radio>
                    <el-radio :label="5">更多</el-radio>
                </el-radio-group>
                <span v-show="saveDuration === 5" class="vidoe-number">
                    <el-input-number 
                        v-model="videoNumber" 
                        :precision="0"
                        :min="13" 
                        :max="36">
                    </el-input-number>月<span style="color: #999">（限制为13～36个月）</span>
                </span>
                <div class="video-duration">单独保存<span style="color: #999">（可对选择的视频单独进行设置保存期限）</span></div>
                <span class="choose-video" @click="chooseVideo">选择视频</span>
                <div class="video-duration" v-if="videoList.length > 0">未保存设置期限的视频列表</div>
                <ul class="video-list" v-if="videoList.length > 0">
                    <li v-for="(item, inx) in videoList" :key="inx">
                        <span><i class="el-icon-video-play video-icon-btn"></i></span>
                        <span>{{item.video_name}}</span>
                        <span>{{item.category}}</span>
                        <span>{{item.user_name}}</span>
                        <span>{{item.size}}</span>
                        <span>{{getMonth(item.saveTime)}}</span>
                        <span @click="deleteVideoList(inx)"><i class="el-icon-error vidoe-delete-btn"></i></span>
                    </li>
                </ul>

                <div class="video-duration">已保存设置期限的视频列表</div>
                <div class="zh-table-contents">
                    <el-table
                        :data="listData"
                        border
                        max-height="600"
                        style="width: 100%">
                        <el-table-column
                            label=""
                            align="center"
                            width="60">
                            <template>
                                <i class="el-icon-video-play video-icon-btn"></i>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="video_name"
                            label="视频名称"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="category"
                            label="分类"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="user_name"
                            label="教师"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="size"
                            label="大小"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="create_time"
                            label="上传时间"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop=""
                            label="保存时间"
                            align="center"
                            show-overflow-tooltip>
                            <template slot-scope="scope">
                                <span>{{getMonth(scope.row.save_month)}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                        prop=""
                        label="操作"
                        align="center"
                        width="80"
                        show-overflow-tooltip>
                            <template slot-scope="scope">
                                <i class="el-icon-error vidoe-delete-btn" @click="deleteRow(scope.row)"></i>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="table-pagination" v-show="listParam.totalNumber > 10">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="listParam.pageIndex"
                            :page-sizes="[10, 20, 30, 40, 50, 100]"
                            :page-size="listParam.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="listParam.totalNumber">
                        </el-pagination>
                    </div>
                </div>
                <el-button type="primary" style="margin-top: 50px" @click="saveSetting">保存设置</el-button>
            </div>
		</div>

        <el-dialog
            title="确认提示"
            :visible.sync="settingVisible"
            :close-on-click-modal="false" 
            :close-on-press-escape="false"
            width="400px">
            <el-input type="password"
                placeholder="请输入超级管理员密码，并确认本次操作。"
                v-model="settingForm.password" 
                @keyup.enter.native="submitPassword"
                autocomplete="off">
            </el-input>
            <div slot="footer" class="dialog-footer">
                <el-button @click="settingVisible = false">取消</el-button>
                <el-button type="primary" @click="submitPassword">确定</el-button>
            </div>
        </el-dialog>

        <el-dialog
            title="选择视频"
            class="choose-dialog"
            :visible.sync="chooseVisible"
            :close-on-click-modal="false" 
            :close-on-press-escape="false"
            width="800px">
            <div class="chose-search">
                <el-input v-model="videoParam.kewword" placeholder="用户名、操作内容"></el-input>
                <el-button type="primary" @click="searchFunc">搜索</el-button>
                <el-button type="primary" @click="restChooseList">重置</el-button>
            </div>
            <div class="zh-table-contents">
                <el-table
                    :data="chooseList"
                    border
                    max-height="600"
                    ref="multipleTable"
                    tooltip-effect="dark"
                    :row-key="getRowKeys"
                    @selection-change="tableSelectionChange"
                    style="width: 100%">
                    <el-table-column
                        type="selection"
                        :reserve-selection="true"
                        :selectable="checkSelectable"
                        width="60"
                        fixed>
                    </el-table-column>
                    <el-table-column
                        prop="video_name"
                        label="视频名称"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="category"
                        label="分类"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="user_name"
                        label="教师"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="size"
                        label="大小"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="create_time"
                        label="上传时间"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                </el-table>

                <div class="table-pagination" v-show="videoParam.totalNumber > 10">
                    <el-pagination
                        @size-change="chooseSizeChange"
                        @current-change="chooseCurrentChange"
                        :current-page="videoParam.pageIndex"
                        :page-sizes="[10, 20, 30, 40, 50, 100]"
                        :page-size="videoParam.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="videoParam.totalNumber">
                    </el-pagination>
                </div>
            </div>
            <el-radio-group v-model="videoParam.chooseDuration" class="video-month">
                <el-radio :label="1" :disabled="saveDuration === 1 ? true : false">永久保存</el-radio>
                <el-radio :label="2" :disabled="saveDuration === 2 ? true : false">三个月</el-radio>
                <el-radio :label="3" :disabled="saveDuration === 3 ? true : false">半年</el-radio>
                <el-radio :label="4" :disabled="saveDuration === 4 ? true : false">一年</el-radio>
                <el-radio :label="5">更多</el-radio>
            </el-radio-group>
            <span v-show="videoParam.chooseDuration === 5" class="vidoe-number">
                <el-input-number 
                    v-model="videoParam.chooseNumber" 
                    :precision="0"
                    :min="13" 
                    :max="36">
                </el-input-number>月<span style="color: #999">（限制为13～36个月）</span>
            </span>

            <div slot="footer" class="dialog-footer">
                <el-button @click="chooseVisible = false">取消</el-button>
                <el-button type="primary" @click="submitChoose">确定</el-button>
            </div>
        </el-dialog>
	</div>
</template>

<script>
  	export default {
	    data() {
		    return {
                saveTransformSetFlag: sessionStorage.getItem('CheckSchoolAppCode') == '00000000000000000000000000000000' ? false : true,
                settingVisible: false, // 确认提示
                chooseVisible: false,// 选择视频
                videoNumber: 13, // 更多 -- 视频博保存时间
                saveDuration: 1, // 频博保存时间
                listData: [], // 视频列表
                selected: [], // 选择的视频
                chooseList: [], // 选择视频列表
                videoList: [], // 准备上传视频列表
                videoListId: [], // 准备上传视频列表 id
 		    	loading: {
					status:false,
					txt:'获取数据...',
                },
                listParam: { // 视频列表参数
                    totalNumber: 0,
                    pageSize: 10,
                    pageIndex: 1
                },
		    	uploadParam:{
		    		teacher_max_size:'',
		    		manage_max_size:'',
		    	},
		    	transformParam:{
		    		immediately_size:'',
		    		work_start_time:'',
		    		work_end_time:'',
                },
                settingForm: {
                    password: ''
                },
                videoParam: { // 视频保存参数
                    kewword: '',
                    chooseDuration: 1,
                    chooseNumber: 13,
                    pageSize: 10,
                    pageIndex: 1,
                    totalNumber: 0
                },
                rules: {
                    password: [
                        { required: true, message: '请输入超级管理员密码', trigger: 'blur'},
                    ]
                },
                loadNumber: 0
		    }
		},
		created(){
            this.getVideoSetting();
        },
        watch: {
            loadNumber() {
				if (this.loadNumber >= 2) {
                    this.loading.status = false;
                }
			}
        },
        computed: {
            getMonth() {
                return (date) => {
                    if (date == 0) {
                        return '永久保存';
                    } else{
                        return date + '个月';
                    }
                }
            }
        },
		methods: {
            checkSelectable(row) {
                if (this.videoListId.includes(row.id)) {
                    return false;
                } else {
                    return true;
                }
		    },
            /**
             * 获取全局视频存储规则
             */
            getGlobalRule() {
                let success = (res => {
                    ++this.loadNumber;
                    
                    switch(res.data.save_month) {
                        case 0:
                            this.saveDuration = 1;
                            break;
                        case 3:
                            this.saveDuration = 2;
                            break;
                        case 6:
                            this.saveDuration = 3;
                            break;
                        case 12:
                            this.saveDuration = 4;
                            break;
                        default:
                            this.videoNumber = res.data.save_month;
                            this.saveDuration = 5;
                    }
                })
				
            	this.$ajax.get('api/video/get_video_global_rule', {func: {success: success}})
            },
            /**
             * 获取视频列表
             */
            getVideoList() {
				let success = (res => {
                    ++this.loadNumber;
                    this.listData = res.data.data;
                    this.listParam.totalNumber = res.data.data_sum;
                })
                let params = {
                    page_size: this.listParam.pageSize,
                    page_index: this.listParam.pageIndex,
                    is_ruled: 1
                }
				
            	this.$ajax.get('api/video/video_ruled_list', {params, func: {success: success}})
            },
            /**
             * row里面有id作为唯一标识
             */
            getRowKeys(row) {
                return row.id;
            },
            tableSelectionChange(val) {
                this.selected = val;
            },
            /**
             * 获取选择视频列表
             */
            getChooseList() {
                this.chooseList = [];
                
				let success = (res => {
					this.chooseList = res.data.data;
                    this.videoParam.totalNumber = res.data.data_sum;

                    let _this = this;
                    let _temp = deep_clone(this.selected);

                    this.$nextTick(() => {
                        // 不可以使用 clearSelection，否则翻页后，选中的数据会被清空
                        for (let i=0; i<_this.chooseList.length; i++) {
                            _this.$refs.multipleTable.toggleRowSelection(_this.chooseList[i], false);
                        }

                        for (let i=0; i<_this.chooseList.length; i++) {
                            for (let j=0; j<_temp.length; j++) {
                                if (_temp[j].id == _this.chooseList[i].id) {
                                    _this.$refs.multipleTable.toggleRowSelection(_this.chooseList[i], true);
                                }
                            }
                        }

                        this.selected = _temp; // 重新赋值，否则删除数据后还是会按上次保存的数据
                    })
                });
                const params = {
                    is_ruled: 0,
                    video_name: this.videoParam.kewword,
                    page_size: this.videoParam.pageSize,
                    page_index: this.videoParam.pageIndex
                }
                
                this.$ajax.get('api/video/video_ruled_list', {params, func: {success: success}})
            },
            /**
            * 搜索列表
            */
            searchFunc() {
                this.videoParam.pageIndex = 1;
                this.getChooseList();
            },
            /**
             * 重置选择视频列表
             */
            restChooseList() {
                this.videoParam.kewword = '';
                this.videoParam.pageSize = 10;
                this.videoParam.pageIndex = 1;

                this.getChooseList();
            },
            /**
             * 显示选择视频弹窗
             */
            chooseVideo() {
                this.chooseVisible = true;
                this.selected = [];

                if (this.saveDuration === 1) {
                    this.videoParam.chooseDuration = 2;
                } else {
                    this.videoParam.chooseDuration = 1;
                }

                this.restChooseList();

                this.videoListId = [];
                this.videoList.forEach(item => {
                    this.videoListId.push(item.id);
                })
            },
            /**
             * 保存选择视频
             */
            submitChoose() {
                if(this.selected.length === 0 ){
					this.$message.warning('请选择视频')
					return false;
                }

                this.chooseVisible = false;

				this.selected.forEach(item => {
                    item.saveTime = this.getSaveTime(this.videoParam.chooseDuration, this.videoParam.chooseNumber);
                    this.videoList.push(item);
                })
            },
            /**
             * 删除没保存视频
             */
            deleteVideoList(inx) {
                this.videoList.splice(inx, 1);
            },
            /**
             * 删除视频数据
             * @param {Object} obj 记录
             */
            deleteRow(obj) {
                let yes = (res => {
					this.deleteData(obj.id);
				})
                let cancel = (res => {})
                
				this.e_confirm({yes: yes, cancel: cancel, txt: `确定将${obj.video_name}删除吗？`});
            },
            /**
             * 删除数据
             * @param {Number} id 要删除的id
             */
            deleteData(id){
		    	let success = (res => {
					this.$message.success(res.msg);
					this.getVideoList();
                });
                let params = {
                    id
                }

		    	this.$ajax.delete('api/video/save_video_rules', {params, func: {success: success}})
            },
            /**
             * 输入密码进行提交
             */
            saveSetting() {
                this.settingVisible = true;
                this.settingForm.password = '';
            },
            /**
             * 验证密码是否正确
             * @param {String} 
             */
            submitPassword() {
                if(this.settingForm.password == '') {
                    this.$message.warning('请输入超级管理员密码')
                    return
                }
                let success = (res => {
                    this.settingVisible = false;
                    this.submitVideo();
                })
                const params = {
                    id: this.$g.user_id,
                    password: this.settingForm.password
                }
                this.$ajax.get("api/user/check_user_by_id", {params, func: {success: success}});
            
            },
            /**
             * 保存视频设置
             */
            submitVideo() {
                this.loading.status = true;
                this.loading.txt = '保存视频设置';
                
                let success = (res => {
                    this.loading.status = false;
                    this.loading.txt = '获取数据';
                    this.settingVisible = false;
                    this.$message.success(res.msg);
                    this.videoList = [];
                    this.selected = [];
                    this.videoListId = [];
                    this.$refs.multipleTable.clearSelection(); // 清空用户的选择，否则会保留之前的选择
                    this.getVideoList();
                })
                let fail = (res => {
                    this.loading.status = false;
                    this.loading.txt = '获取数据';
                    this.$message.error(res.msg);
                })

                let month = this.getSaveTime(this.saveDuration, this.videoNumber);
                let id = '0';

                this.videoList.forEach(item => {
                    id += ',' + item.id;
                    month += ',' + item.saveTime;
                })

                let params = {id, month};
                
                this.$ajax.post('api/video/save_video_rules', params, {func: {success: success, fail: fail}})
            },
            /**
             * 获取保存时间
             */
            getSaveTime(time1, time2) {
                let month = 0;

                switch(time1) {
                    case 1:
                        month = 0;
                        break;
                    case 2:
                        month = 3;
                        break;
                    case 3:
                        month = 6;
                        break;
                    case 4:
                        month = 12;
                        break;
                    case 5:
                        month = time2;
                        break;
                }

                return month;
            },
			proving(val) {
				this.$nextTick(() => {
					this.uploadParam.teacher_max_size = parseInt(Math.floor(val));
				})
			},
			manageSise(val) {
				this.$nextTick(() => {
					this.uploadParam.manage_max_size = parseInt(Math.floor(val));
				})
			},
			immediatelySise(val) {
				this.$nextTick(() => {
					this.transformParam.immediately_size = parseInt(Math.floor(val));
				})
			},
			getVideoSetting(){
				this.loading.status = true;
				let success = (data=>{
            		this.uploadParam = data.data.upload_setting;
                    this.transformParam = data.data.transform_setting;
                    
                    // 视频保存设置
                    this.getGlobalRule();
                    this.getVideoList();
            	})
            	let fail = ( data => {
            		this.loading.status = false
            		this.$message.error(data.msg)
				})
				
            	//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
            	this.$ajax.get('api/video/video_setting',{func:{success:success,fail:fail}})
            },
			saveUploadSetting(){
				let success = ( data=>{
	            		this.$message.success(data.msg);
					})
				if(this.uploadParam.teacher_max_size === undefined || this.uploadParam.manage_max_size === undefined) {
					this.$message.error('请填写完整信息');
					return;
				} else {
					this.$ajax.put('api/video/save_video_upload_setting',this.uploadParam,{func:{success:success}})
				}
			},
			saveTransformSetting(){
				let success = ( data=>{
	            		this.$message.success(data.msg);
					})
				if(this.transformParam.immediately_size === undefined) {
					this.$message.error('请填写完整信息');
					return;
				} else {
					this.$ajax.put('api/video/save_video_transform_setting',this.transformParam,{func:{success:success}})
				}
            },
            /**
             * 切换当前页数据数量
             * @param {Number} val 数量
             */
            handleSizeChange(val) {
		    	this.listParam.pageIndex = 1;
                this.listParam.pageSize = val;
                
		    	this.getVideoList()
            },
            /**
             * 切换到某页
             * @param {Number} val 页数
             */
		    handleCurrentChange(val) {
                this.listParam.pageIndex = val;
                
		    	this.getVideoList();
            },
            /**
             * 切换当前页数据数量
             * @param {Number} val 数量
             */
            chooseSizeChange(val) {
		    	this.videoParam.pageIndex = 1;
                this.videoParam.pageSize = val;
                
		    	this.getChooseList()
            },
            /**
             * 切换到某页
             * @param {Number} val 页数
             */
		    chooseCurrentChange(val) {
                this.videoParam.pageIndex = val;
                
		    	this.getChooseList();
		    },
		},
  	}
</script>

<style lang="scss">
	.zh-video-settings {
        .video-list {
            padding: 20px;
            max-height: 390px;
            background: #F2F2F2;
            overflow: hidden;
            overflow-y: auto;

            li {
                height: 40px;
                line-height: 40px;

                span {
                    display: inline-block;
                    width: 120px;
                    text-align: center;
                    text-overflow:ellipsis;
                    white-space: nowrap;
                    overflow: hidden;
                }

                span:first-child {
                    width: 22px;
                    text-align: left;
                }
            }
        }

		.zh-video-test {
			h3 {
				padding-top: 20px;
			}
			.zh-video-directions {
				height: 40px;
				line-height: 40px;
			}
			.zh-video-number {
				margin-bottom: 20px;
				.el-date-editor {
					width: 130px;
				}
			}
		}

        .video-duration {
            margin: 30px auto 20px;
        }

        .choose-video {
            display: block;
            margin-bottom: 40px;
            text-align: center;
            width: 88px;
            height: 30px;
            line-height: 30px;
            color: #348EFC;
            border: 1px solid #348EFC;
            border-radius: 4px;
            box-sizing: border-box;
            cursor: pointer;
        }

        .video-month {
            height: 30px;
            line-height: 40px;
        }

        .vidoe-number {
            display: inline-block;
            margin-left: 45px;
            vertical-align: top;

            .el-input-number {
                width: 70px;
            }

            .el-input-number__decrease,
            .el-input-number__increase  {
                display: none;
            }

            .el-input {
                width: 70px;
                height: 28px;
                line-height: 28px;

                input {
                    padding: 0;
                    width: 60px;
                    height: 30px;
                    line-height: 30px;
                }
            }
        }

        .video-icon-btn {
            color: #000;
            font-size: 20px;
            vertical-align: middle;
        }

        .vidoe-delete-btn {
            color: #D3D3D3;
            font-size: 20px;
            cursor: pointer;
            vertical-align: middle;
        }

        .vidoe-delete-btn:hover {
            color: #f56c6c;
        }

        .choose-dialog {
            .chose-search {
                >div {
                    margin-right: 20px;
                    width: 220px;
                }
            }

            .zh-table-contents {
                margin: 30px auto 60px;
            }

            .video-month {
                margin-bottom: 40px;
            }
        }
	}
</style>